<?php
/**
 * Created by PhpStorm.
 * User: 86151 - 姜伟
 * Date: 2022/8/31 21:47.
 */

namespace Xinyu\Gen\Core\Libs;

use Xinyu\Gen\Core\Config\CommonConfig;
use Illuminate\Support\Str;

class CreateClient extends BaseClient
{
    use SingletonUtil;

    // 生成文件
    public function createFile($type = 'Controller', $params = [], $savePath = '')
    {
        if (empty($params)) {
            return [];
        }
        $name = $params['name'] ?? '';
        if (empty($name)) {
            return $this->error('name不能为空');
        }
        $extendReplaces = $params['extend_replaces'] ?? [];
        $name = Str::studly($name);
        $caseName = Str::snake($name);
//        $filePath = app_path("/Console/Commands/Gen/Template/Template{$type}.stub");
        $filePath = __DIR__ . "/../../Commands/Template/Template{$type}.stub";
        $file = file_get_contents($filePath);
        $module = Str::studly($params['module'] ?? CommonConfig::MODULE_ADMIN);
        $searchList = ['{$name}', '{$caseName}', '{$module}'];
        $replaceList = [$name, $caseName, $module];
        if (!empty($extendReplaces)) {
            foreach ($extendReplaces as $k => $v) {
                $searchList[] = '{$' . Str::camel($k) . '}';
                $replaceList[] = $v;
            }
        }
        $file = str_replace($searchList, $replaceList, $file);
        if (file_exists($savePath)) {
            return $this->error("{$module}{$params['save_path']}{$type}.php已存在");
        }
        file_put_contents($savePath, $file);
        return $this->success("{$module}{$params['save_path']}{$type}.php生成成功");
    }
}
